<template>
  <div class="login">
    <h1 class="title">登录</h1>
    <van-form>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div>
        <van-button round block type="info" native-type="submit" @click.native="login">提交</van-button>
      </div>
    </van-form>
    <div class="register">
      <a href="javascript:;" @click="register">注册</a>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: "",
      password: ""
    };
  },
  methods: {
    register() {
      this.$router.push("/register");
    },
    login() {
      if (this.username && this.password) {
        this.$axios({
          url: "/login",
          method: "post",
          data: {
            uname: this.username,
            pasw: this.password
          }
        }).then(
          res => {
            // console.log(res);
            if (res.code) {
              localStorage.setItem("uid", res.sult.id);
              this.$dialog({
                message:
                  "亲爱的" + res.sult.user_name + "，你妈了个巴子，欢迎回来"
              }).then(res => {
                this.$router.push("/");
                this.$store.commit("updateUserId", localStorage.getItem("uid"));
              });
            } else {
              console.log(res.msg);
              this.$dialog
                .confirm({
                  message: res.msg + ",请重新登录",
                  confirmButtonText: "去注册",
                  cancelButtonText: "确认"
                })
                .then(() => {
                  // on confirm
                  this.$router.push("/register");
                })
                .catch(() => {
                  // on cancel
                });
            }
          },
          err => {
            console.log(err);
          }
        );
      }
    }
  },
  created() {}
};
</script>

<style lang="less" scoped>
.login {
  .title {
    text-align: center;
    font-weight: 400;
    padding: 10px;
  }
  .register {
    text-align: center;
    padding: 10px;
    a {
      color: royalblue;
      border-bottom: 1px solid royalblue;
    }
  }
  background-color: #fff;
  margin-top: 40%;
}
</style>